fetch("/api/caipiao/getRecent10Records")
    .then(response => response.json())
    // .then(response => response.text())
    .then(result => {
        renderHistoryTable(result);
        renderResultTable(result);
    })
    .catch(err => console.log('Request Failed', err));


const renderHistoryTable = (list) => {
    let htmlText = list.map(row => {
        let html = `
        <tr>
            <td>${row.code}</td>
            <td>${row.red.map(n => `<span class="circle red">${fillZero(n)}</span>`).join(" ")}</td>
            <td><span class="circle blue">${fillZero(row.blue)}</span></td>
        </tr>
        `;
        return html;
    })
    document.querySelector(".history-data").innerHTML = htmlText.join("");
}

function fillZero(num) {
    if (num < 10) {
        return "0" + num;
    } else {
        return "" + num;
    }
}

/**
 * 获取随机数,默认是 0-10
 * @param {number} minValue
 * @param {number} maxValue
 * @param {boolean} includeMaxValue 是否包含最大值
 */
let getRandom = function (minValue, maxValue, includeMaxValue) {
    if (minValue === undefined) {
        minValue = 0;
    }
    if (maxValue === undefined) {
        maxValue = 10;
    }
    if (includeMaxValue === undefined) {
        includeMaxValue = false;
    }
    let exp1;
    if (includeMaxValue) {
        exp1 = (maxValue - minValue + 1);
    } else {
        exp1 = (maxValue - minValue);
    }

    let retObj = {
        next: function () {
            return Math.floor(Math.random() * exp1) + minValue;
        }
    };

    return retObj;
}

const renderResultTable = (list) => {
    let reds = list.map(r => r.red).reduce((a, b) => a.concat(b)).sort((a, b) => a - b);
    let blues = list.map(r => r.blue).sort((a, b) => a - b);
    //统计红球数量，数量最多的三个必选，剩余三个随机
    //统计蓝球数量，蓝球为数量最多的两个，二选一
    let redsCount = {};
    let bluesCount = {};
    for (let i = 0; i < reds.length; i++) {
        const item = reds[i];
        if (redsCount[item] === undefined) {
            redsCount[item] = 0;
        }
        redsCount[item] += 1;
    }

    for (let j = 0; j < blues.length; j++) {
        const item = blues[j];
        if (bluesCount[item] === undefined) {
            bluesCount[item] = 0;
        }
        bluesCount[item] += 1;
    }
    let redsCountList = [];
    let bluesCountList = [];
    for (const key in redsCount) {
        if (Object.hasOwnProperty.call(redsCount, key)) {
            const item = redsCount[key];
            redsCountList.push({ key, value: redsCount[key] });
        }
    }

    for (const key in bluesCount) {
        if (Object.hasOwnProperty.call(bluesCount, key)) {
            const item = bluesCount[key];
            bluesCountList.push({ key, value: bluesCount[key] });
        }
    }
    redsCountList = redsCountList.sort((a, b) => b.value - a.value).map(x => parseInt(x.key));
    bluesCountList = bluesCountList.sort((a, b) => b.value - a.value).map(x => parseInt(x.key));
    let newRedList = redsCountList.splice(0, 3);
    let newBlueList = bluesCountList.splice(0, 2);
    //生成五组号码
    let resultList = [];
    let ranRed = getRandom(0, redsCountList.length, false);
    let ranBlue = getRandom(0, 42, true);
    for (let lucky = 0; lucky < 5; lucky++) {
        let redList = newRedList.concat([]);
        let usedIdx = [];
        for (let lucky2 = 0; lucky2 < 3; lucky2++) {
            let luckyIdx = ranRed.next();
            let value = redsCountList[luckyIdx];
            let isExist = true;
            while (isExist) {
                for (let lucky3 = 0; lucky3 < usedIdx.length; lucky3++) {
                    const usedIdxItem = usedIdx[lucky3];
                    if (usedIdxItem === luckyIdx) {
                        isExist = true;
                        luckyIdx = ranRed.next();
                        value = redsCountList[luckyIdx];
                        break;
                    }
                }
                isExist = false;
                usedIdx.push(luckyIdx)
            }
            redList.push(value);
        }
        resultList.push({
            lucky: lucky + 1,
            red: redList.sort((a, b) => a - b),
            blue: newBlueList[ranBlue.next()%2]
        });
    }
    let htmlText = resultList.map(row => {
        let html = `
        <tr>
            <td>${row.lucky}</td>
            <td>${row.red.map(n => `<span class="circle red">${fillZero(n)}</span>`).join(" ")}</td>
            <td><span class="circle blue">${fillZero(row.blue)}</span></td>
        </tr>
        `;
        return html;
    })
    document.querySelector(".result-data").innerHTML = htmlText.join("");
}